//
//  CMDeviceUtils.swift
//  covermedia
//
//  Created by Travel on 16/1/25.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import Foundation
import KeychainAccess

open class CMDefaultKeychain {
    static let shared = Keychain(service: Bundle.main.bundleIdentifier!)
}

open class CMDeviceUtils {
    fileprivate static let kIdentifier = "kCMIdentifier"

    open class func getDeviceId() -> String {
        var deviceId: String = ""
        if let deviceIdInUserDefault = UserDefaults.standard.string(forKey: kIdentifier) {
            deviceId = deviceIdInUserDefault
        } else if let result = try? CMDefaultKeychain.shared.getString(kIdentifier), let deviceIdInKeychain = result, !deviceIdInKeychain.isEmpty {
            deviceId = deviceIdInKeychain
            UserDefaults.standard.set(deviceId, forKey: kIdentifier)
        }
        
        if deviceId.isEmpty {
            deviceId = UUID.init().uuidString
            UserDefaults.standard.set(deviceId, forKey: kIdentifier)
            _ = try? CMDefaultKeychain.shared.set(deviceId, key: kIdentifier)
        }
        return deviceId
    }

}
